package com.ddch.testioc.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * created by 韦敏敏
 * on 2019/12/17
 */
public class Main {
    private Button button = new Button();
    public Main() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        init();
    }
    public void click(){
        System.out.println("Button Clicked!");
    }
    private void init() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IllegalArgumentException{
        try {
            OnClickListenerHandler handler = new OnClickListenerHandler(this);
            Method method = Main.class.getMethod("click", null);
            handler.addMethod("onClick", method);
            Object clickProxy = Proxy.newProxyInstance(OnClickListener.class.getClassLoader(),
                    new Class<?>[]{OnClickListener.class},
                    handler);
            Method clickMethod = button.getClass().getMethod("setOnClickListener", OnClickListener.class);
            clickMethod.invoke(button, clickProxy);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Main main = new Main();
        main.button.click();
    }
}
